// pages/myself/myspellgroup/MySpellGroupDetails.js
var Zan = require('../../../dist/index');
var WxParse = require('../../../wxParse/wxParse.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
function countdown(that) {
    var EndTime = that.data.endtime || [];
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];
    // 渲染倒计时时钟
    that.data.groupsellDetail.clock = dateformat(total_micro_second)
    // that.setData({
    //   clock: dateformat(total_micro_second)
    // });
    if (total_micro_second <= 0) {
      that.data.groupsellDetail.clock = "已经截止"
      //return;
    }

  that.setData({
    groupsellDetail: that.data.groupsellDetail
  })
  setTimeout(function () {
    total_micro_second -= 1000;
    countdown(that);
  }
    , 1000)
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  if (day>0){
    hr=hr+day*24
    return hr + ":" + min + ":" + sec;
  }else{
    return hr + ":" + min + ":" + sec;
  }
  
}
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    shared: true,
    product: {},
    showDialog: false,
    count: 1,
    price: 0,
    distributorId: "",
    spellGroup: null,
    specDetails: '',
    userSpellGroupId: '',
    mobile: null,
    groupCount: 0,
    groupsellDetail: [],
    cantuanlist: [],
    formId: '',
    sgCombId:null,
    endtime:'',
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();


    try {
      var value = wx.getStorageSync('Cantuan_spec')
      if (value) {
        // Do something with return value
        this.setData({
          Cantuan_spec: value,
        })
      }
    } catch (e) {
      // Do something when catch error
    }

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        bind(options);
      }
    }

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    wx.getUserInfo({
      success: res => {
        this.setData({
          nickName: res.userInfo.nickName,
        })
      }
    })

    this.setData({
      userSpellGroupId: options.userSpellGroupId,
      spellGroupsId: options.spellGroupsId,
      tuantype: options.type,
      endtime: options.endtime,
      originator: options.originator
    })
    if (options.sgCombId){
      this.setData({
        sgCombId: options.sgCombId
      })
    }
    // network._post_json(this, api.getProductDetails, { productId: options.productId }, detailsSuccess);
    // network._post_json(this, api.groupRule, { spellgroupId: this.data.userSpellGroupId }, ruleSuccess);
    network._post_json(this, api.spellGroupsActiveDetail, { sgCombId: this.data.sgCombId, spellGroupsId: this.data.spellGroupsId, status: this.data.tuantype, originator: this.data.originator }, Success);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '花' + parseInt(this.data.groupsellDetail.sgPrice) / 100 + '元，就能拼得原价' + parseInt(this.data.groupsellDetail.danmaiprice) / 100 + '元的【' + this.data.groupsellDetail.sgName + '】，太超值了',
      path: '/pages/product/SpellGroupDetails?shared=' + app.globalData.userAndTenantInfo.id + '&spellGroupId=' + this.data.spellGroupsId + '&userSpellGroupId=' + this.data.userSpellGroupId,
      // imageUrl: this.data.saleInfo.qrCode,
      success: function (res) {
        // 转发成功
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets,
            success: function (res) {
              network._post_json(that, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
            },
            fail: function (res) {
              // 转发失败
              network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
            }
          })
        } else {
          network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog,
      count: 1,
    })
    allPrice(this, this.data.spellGroup);
  },

  /**
   * 进入下一步提交订单
   */
  next: function (e) {
    this.setData({
      showDialog: false,
      count: this.data.count,
    });

    startPay(this);
  },


  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      this.setData({
        count: this.data.count
      });
      allPrice(this, this.data.spellGroup);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    // 判断是否超过限购数量
    if (this.data.count < this.data.spellGroup.confineCount) {
      this.data.count++;
      this.setData({
        count: this.data.count
      });
      allPrice(this, this.data.spellGroup);
    } else {
      this.showZanTopTips('您已达到限购数量');
    }

  },

  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  chooseSpan: function (e) {
    if (this.data.product.isVirtual == 0 && this.data.product.isActive == 1) {
      this.setData({
        showDialog: true,
      });
    } else {
      this.showZanTopTips('商品已下架');
    }
  },

  formSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },

  refresh(count) {
    this.setData({
      groupCount: this.data.groupCount - 1
    })
    if (parseInt(this.data.groupCount) <= 0) {
      this.setData({
        groupCount: 0
      })
    }

    var user = {
      avatarUrl: app.globalData.userAndTenantInfo.avatarUrl,
      nickName: app.globalData.userAndTenantInfo.nickName
    }
    this.data.spellGroup.user = user;
    this.setData({
      spellGroup: this.data.spellGroup
    })
  },
  //查看更多
  groupMore: function () {
    wx.navigateTo({
      url: '/pages/product/SpellGroupMore'
    })
  },
  //时间截止
  clikNow:function(e){
    this.showZanTopTips(this.prompt, '拼团时间截止，下次早点来！');
  }
}))

/**
 * 计算所选商品的总价
 */
var allPrice = function (that, item) {
  that.setData({
    price: item.proGroupPrice * that.data.count
  })
}

// 获取商品详情结果
// var detailsSuccess = function (that, res) {
//   if (res.data.data) {
//     that.setData({
//       product: res.data.data.product,
//     })
//     WxParse.wxParse('details', 'html', res.data.data.sgdetails, that, 0);
//   }
// }

var startPay = function (that) {
  var product = {};
  var products = [];
  product.id = that.data.product.id;
  product.title = that.data.product.title;
  product.smallImgUrl = that.data.product.smallImgUrl;
  product.conMode = that.data.product.conMode
  product.count = that.data.count;
  product.price = that.data.spellGroup.proGroupPrice;
  product.specId = that.data.spellGroup.productSpecId;
  product.specName = that.data.spellGroup.proSpecification;
  products.push(product);

  try {
    wx.setStorageSync('spell_products', products)
  } catch (e) {
  }

  wx.navigateTo({
    url: '/pages/pay/SpellPay?spellGroupId=' + that.data.spellGroup.id
  })
}

var bindSuccess = function (that, res) {
  if (that.data.formId && app.globalData.userAndTenantInfo.mobile != res.data.data.mobile) {
    network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 2 }, sendCoupnSuccess);
  }
  
  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var ruleSuccess = function (that, res) {
  that.setData({
    spellGroup: res.data.data[0],
    // price: res.data.data.proGroupPrice,
    groupCount: parseInt(res.data.data[0].groupSuccCount) - parseInt(res.data.data[0].groupCount)
  })
  if (parseInt(that.data.groupCount) <= 0) {
    that.setData({
      groupCount: 0
    })
  }
  allPrice(that, res.data.data[0]);
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var Success = function (that, res) {
  if (res.data.data.specType1 && !res.data.data.specType2 && !res.data.data.specType3) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1
  }
  if (res.data.data.specType2 && !res.data.data.specType3) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1 + '   ' + res.data.data.specType2 + ':' + res.data.data.spellGroupsComb.specDetails2
  }
  if (res.data.data.specType3) {
    res.data.data.spellGroupsComb.specDetails = res.data.data.specType1 + ':' + res.data.data.spellGroupsComb.specDetails1 + '   ' + res.data.data.specType2 + ':' + res.data.data.spellGroupsComb.specDetails2 + '   ' + res.data.data.specType3 + ':' + res.data.data.spellGroupsComb.specDetails3
  }

  if (res.data.data.spellGroupsDetails && res.data.data.spellGroupsDetails.length > 0) {
    for (var i = 0; i < res.data.data.spellGroupsDetails.length; i++) {
      if (res.data.data.spellGroupsDetails[i].originator == res.data.data.spellGroupsDetails[i].userId) {
        //获取团长购买的数量
        res.data.data.count = res.data.data.spellGroupsDetails[i].orderProductDetail.count;
        res.data.data.pintuanprice = res.data.data.spellGroupsDetails[i].orderProductDetail.price2
        res.data.data.danmaiprice = res.data.data.spellGroupsDetails[i].orderProductDetail.price
        break;
      }
    }
  }

  var Totalsum = 0;
  for (var i = 0; i < res.data.data.spellGroupsDetails.length; i++) {
    Totalsum += res.data.data.spellGroupsDetails[i].orderProductDetail.count
  }
  if (res.data.data) {
    that.setData({
      groupsellDetail: res.data.data,
      specDetails: res.data.data.spellGroupsComb ? res.data.data.spellGroupsComb.specDetails : '',
      cantuanlist: res.data.data.spellGroupsDetails.reverse(),
      Totalsum: Totalsum
    })
  }
  
  WxParse.wxParse('details', 'html', res.data.data.sgdetails, that, 0);
  countdown(that);
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}

var sendCoupnSuccess = function (that, res) { }